<template>
  <div class="container">
    <div class="con">
      <!-- 左侧树 -->
      <div class="left-tree">
        <a-tree
          v-model:expandedKeys="expandedKeys"
          :selectedKeys="selectedKeys"
          v-model:checkedKeys="checkedKeys"
          :tree-data="treeData"
          @click="handleClick"
        >
          <template #title="{ title, key }">
            <span v-if="key === '0-0-1-0'" style="color: #1890ff">{{ title }}</span>
            <template v-else>{{ title }}</template>
          </template>
        </a-tree>
      </div>

      <!-- 右侧树及按钮 -->
      <div class="right-content">
        <div class="right-header">
          <span>{{ title }}</span>
        </div>
        <div class="bbt">
          <a-button
            type="primary"
            size="small"
            @click="openModal(false)"
            :icon="h(PlusOutlined)"
            >添加同级节点</a-button
          >
          <a-button
            type="primary"
            size="small"
            @click="openModal(true)"
            :icon="h(PlusOutlined)"
            >添加下级节点</a-button
          >
          <a-button
            type="primary"
            size="small"
            @click="deleteNode"
            :icon="h(MinusOutlined)"
            >删除</a-button
          >
          <a-button
            type="primary"
            size="small"
            @click="moveUpNode"
            :icon="h(ArrowUpOutlined)"
            >上移</a-button
          >
          <a-button
            type="primary"
            size="small"
            @click="moveDownNode"
            :icon="h(ArrowDownOutlined)"
            >下移</a-button
          >
        </div>
        <a-tree
          v-model:expandedKeys="expandedKeys"
          :selectedKeys="selectedKeys"
          v-model:checkedKeys="checkedKeys"
          :tree-data="rightTreeData"
          @click="handleRightTreeClick"
          @select="handleRightTreeSelect"
        >
          <template #title="{ title, key, record }">
            <div class="tree-node-container">
              <span>{{ title }}</span>
              <!-- 添加textarea，仅对二级节点显示 -->
              <template v-if="isSecondLevelNode(key)">
                <a-textarea
                  v-model:value="value"
                  :rows="1"
                  :placeholder="findTypeByKey(key)"
                ></a-textarea>
              </template>
            </div>
          </template>
        </a-tree>
      </div>
    </div>

    <!-- 添加节点的模态框 -->
    <a-modal
      v-model:open="showModal"
      title="添加节点"
      ok-text="确定"
      cancel-text="取消"
      @ok="addNode"
      @cancel="closeModal"
    >
      <a-input v-model:value="inputValue" placeholder="请输入节点名称"></a-input>
    </a-modal>

    <!-- 底部操作栏 -->
    <div class="footer">
      <a-button type="primary" size="small" @click="previewTemplate">模板预览</a-button>
      <a-button type="primary" size="small" @click="saveTemplate">保存模板</a-button>
      <a-select
        v-model="selectedParentMenu"
        style="width: 200px"
        placeholder="选择上级菜单"
      >
        <a-select-option
          v-for="item in parentMenuOptions"
          :key="item.key"
          :value="item.key"
        >
          {{ item.title }}
        </a-select-option>
      </a-select>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ArrowDownOutlined,
  ArrowUpOutlined,
  MinusOutlined,
  PlusOutlined,
} from "@ant-design/icons-vue";
import type { TreeProps } from "ant-design-vue";
import { h, ref, watch } from "vue";

// 左侧树数据
const treeData: TreeProps["treeData"] = [
  {
    title: "框架模板v.13",
    key: "0-0",
    children: [
      {
        title: "2023年度模版",
        key: "0-0-0",
        children: [{ title: "ABC公司 2023年度报告模版", key: "0-0-0-0" }],
      },
      {
        title: "2023年度模版",
        key: "0-0-1",
        children: [{ key: "0-0-1-0", title: "XYZ公司 2024年度报告" }],
      },
    ],
  },
];

// 右侧树数据
const rightTreeData = ref([
  // Your existing rightTreeData here
]);

const title = ref(""); // 右侧标题区域显示的名称
const expandedKeys = ref<string[]>(["0-0", "0-0-0"]);
const checkedKeys = ref<string[]>([]);
const selectedKeys = ref<string[]>([]); // 选中的节点
const selectedNodeKey = ref<string | null>(null); // 当前选中的节点key
const inputValue = ref(""); // 用于存储输入框的值
const showModal = ref(false); // 控制模态框的显示
const isChildNode = ref(false); // 控制添加节点类型（是否为下级节点）
const findTypeByKey = (key: string): string | undefined => {
  const node = findNodePosition(key, rightTreeData.value);
  return node?.parent?.children[node.index]?.type;
};
const value = ref("");
const parentMenuOptions = ref([
  { key: "menu1", title: "Menu 1" },
  { key: "menu2", title: "Menu 2" },
  { key: "menu3", title: "Menu 3" },
]);
const selectedParentMenu = ref("");

// 模板预览
const previewTemplate = () => {
  console.log("Preview template");
  // Add your logic to preview the template, e.g., show a modal or navigate to a preview page
};

// 保存模板
const saveTemplate = () => {
  console.log("Save template");
  // Add your logic to save the template, potentially using `selectedParentMenu.value`
};

watch(expandedKeys, () => {
  console.log("expandedKeys", expandedKeys);
});

watch(checkedKeys, () => {
  console.log("checkedKeys", checkedKeys);
});

watch(selectedKeys, (newKeys) => {
  if (newKeys.length > 0) {
    const key = newKeys[0];
    selectedNodeKey.value = key;
  } else {
    selectedNodeKey.value = null;
  }
});

let clickTimer: NodeJS.Timeout | null = null;
const doubleClickThreshold = 300; // 300ms for double click

const handleClick = (event: Event, node: any) => {
  if (clickTimer) {
    clearTimeout(clickTimer);
    clickTimer = null;
    handleDoubleClick(node);
  } else {
    clickTimer = setTimeout(() => {
      clickTimer = null;
    }, doubleClickThreshold);
  }
};

const handleDoubleClick = (node: any) => {
  const { key } = node;
  selectedKeys.value = [key];
  title.value = node.dataRef.title;
  console.log("Node double clicked:", node);
};

// 查找节点在树中的位置
const findNodePosition = (
  key: string,
  nodes: any[]
): { parent: any; index: number } | null => {
  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    if (node.key === key) {
      return { parent: null, index: i };
    }
    if (node.children) {
      const result = findNodePosition(key, node.children);
      if (result) {
        return { parent: node, index: result.index };
      }
    }
  }
  return null;
};

// 打开模态框
const openModal = (isChild: boolean) => {
  inputValue.value = ""; // 清空输入框
  isChildNode.value = isChild;
  showModal.value = true;
};

// 关闭模态框
const closeModal = () => {
  showModal.value = false;
};

// 添加节点
const addNode = () => {
  if (!inputValue.value) return; // 没有输入值则不操作

  const newNode = { title: inputValue.value, key: `${Date.now()}`, children: [] };
  if (selectedNodeKey.value) {
    const nodePosition = findNodePosition(selectedNodeKey.value, rightTreeData.value);
    if (nodePosition) {
      const { parent, index } = nodePosition;
      if (isChildNode.value) {
        if (parent) {
          parent.children[index].children.push(newNode);
        } else {
          rightTreeData.value[index].children.push(newNode);
        }
      } else {
        if (parent) {
          parent.children.splice(index + 1, 0, newNode);
        } else {
          rightTreeData.value.splice(index + 1, 0, newNode);
        }
      }
    }
  }
  closeModal();
};

// 删除节点
const deleteNode = () => {
  if (selectedNodeKey.value) {
    const nodePosition = findNodePosition(selectedNodeKey.value, rightTreeData.value);
    if (nodePosition) {
      const { parent, index } = nodePosition;
      if (parent) {
        parent.children.splice(index, 1);
      } else {
        rightTreeData.value.splice(index, 1);
      }
    }
  }
};

// 节点上移
const moveUpNode = () => {
  if (selectedNodeKey.value) {
    const nodePosition = findNodePosition(selectedNodeKey.value, rightTreeData.value);
    if (nodePosition) {
      const { parent, index } = nodePosition;
      if (parent) {
        const node = parent.children.splice(index, 1)[0];
        parent.children.splice(index - 1, 0, node);
      } else {
        const node = rightTreeData.value.splice(index, 1)[0];
        rightTreeData.value.splice(index - 1, 0, node);
      }
    }
  }
};

// 节点下移
const moveDownNode = () => {
  if (selectedNodeKey.value) {
    const nodePosition = findNodePosition(selectedNodeKey.value, rightTreeData.value);
    if (nodePosition) {
      const { parent, index } = nodePosition;
      if (parent) {
        const node = parent.children.splice(index, 1)[0];
        parent.children.splice(index + 1, 0, node);
      } else {
        const node = rightTreeData.value.splice(index, 1)[0];
        rightTreeData.value.splice(index + 1, 0, node);
      }
    }
  }
};

// 右侧树节点点击事件
const handleRightTreeClick = (event: Event, node: any) => {
  console.log("Right tree node clicked:", node);
};

// 右侧树节点选择事件
const handleRightTreeSelect = (selectedKeys: string[], info: any) => {
  console.log("Selected right tree keys:", selectedKeys);
  if (selectedKeys.length > 0) {
    const key = selectedKeys[0];
    selectedNodeKey.value = key;
    title.value = info.node.title;
  }
};

// 检查是否为二级节点
const isSecondLevelNode = (key: string) => {
  const node = findNodePosition(key, rightTreeData.value);
  return node ? node.parent?.key === "0-0-1" : false;
};
</script>

<style scoped lang="less">
@import "./index.less";

/* 样式调整，根据需要修改 */
.container {
  display: flex;
  flex-direction: column;
}

.con {
  display: flex;
  margin-top: 0px;
}

.left-tree {
  flex: 1;
  overflow: auto;
}

.right-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: auto;
}

.right-header {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.right-content .ant-tree {
  margin-bottom: 10px;
}

textarea {
  margin-top: 5px;
  width: 420px;
}

.tree-node-container {
  display: flex;
  flex-direction: column;
}

.footer {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  background-color: #f0f2f5;
  border-top: 1px solid #d9d9d9;
}
</style>
